﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace iPhotoUploader.Library
{
    public class Album
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public AlbumImage ListingImage { get; set; }
        public XmlNodeList ImagesXml { get; set; }
        public List<AlbumImage> Images { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }

        public Album(XmlNode node, List<AlbumImage> allImages)
        {
            Id = node.SelectSingleNode("key[normalize-space(text())='RollID']").NextSibling.InnerText;
            Name = node.SelectSingleNode("key[normalize-space(text())='RollName']").NextSibling.InnerText;
            string listingIamgeId = node.SelectSingleNode("key[normalize-space(text())='KeyPhotoKey']").NextSibling.InnerText;
            ListingImage = allImages.Where(item => item.Id == listingIamgeId).FirstOrDefault();
            ImagesXml = node.SelectSingleNode("array").ChildNodes;
            GetImages(allImages);
        }

        public static List<Album> LoadAllAlbums(XmlDocument xml, List<AlbumImage> allImages)
        {
            XmlNodeList albumsXml = xml.SelectSingleNode("plist/dict/key[normalize-space(text())='List of Rolls']").NextSibling.ChildNodes;
            List<Album> albums = new List<Album>();

            foreach (XmlNode albumNode in albumsXml)
            {
                Album album = new Album(albumNode, allImages);

                if(album != null && !album.Name.Equals("photo stream", StringComparison.OrdinalIgnoreCase))
                    albums.Add(new Album(albumNode, allImages));
            }

            return albums;
        }

        protected List<AlbumImage> GetImages(List<AlbumImage> allImages)
        {
            Images = new List<AlbumImage>();
            foreach (XmlNode imagesXmlNode in ImagesXml)
            {
                Images.Add(allImages.Where(image => image.Id == imagesXmlNode.InnerText).FirstOrDefault());
            }

            return Images;

        }
    }
}
